using UnityEngine;
using Unity.VisualScripting;
using GameFramework;
using GameFramework.DataTable;
using UnityGameFramework.Runtime;

namespace LS.UGFUnits
{
    [UnitShortTitle("Data Table")]
    [UnitSurtitle("Parse Data")]
    public sealed class ParseDataTable : DataTableUnit
    {
        [Serialize]
        [Inspectable, UnitHeaderInspectable]
        [TypeFilter(typeof(DataRowBase))]
        public System.Type DataTableType { get; set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueInput DataTableInstance { get; private set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueInput DataString { get; private set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueInput UserData { get; private set; }
        
        [DoNotSerialize] 
        [PortLabelHidden]
        public ValueOutput Result { get; private set; }
        
        protected override void Definition()
        {
            base.Definition();
            DataString =  ValueInput<string>(nameof(DataString));
            DataTableInstance  = ValueInput<DataTableBase>(nameof(DataTableInstance));
            UserData =  ValueInput<object>(nameof(UserData));
            Result = ValueOutput<bool>(nameof(Result));
            Requirement(DataTableInstance, Input);
            Requirement(DataString, Input);
            Requirement(UserData, Input);
        }

        protected override ControlOutput In(Flow flow)
        {
            string dataString = flow.GetValue<string>(DataString);
            bool result = false;
            DataTableBase dataTable = flow.GetValue<DataTableBase>(DataTableInstance);
            object userData = flow.GetValue<object>(UserData);
            if (dataTable != null)
            {
                result = dataTable.ParseData(dataString,userData ?? flow.stack.gameObject);
            }
            flow.SetValue(Result, result);
            return Output;
        }
    }
}